package sk.fritz.megafonsms;

import java.io.IOException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import sk.fritz.megafonsms.formmodel.Builder;
import sk.fritz.megafonsms.formmodel.FormModel;
import sk.fritz.megafonsms.formmodel.InputFormControl;
import sk.fritz.megafonsms.formparser.FormParser;
import sk.fritz.megafonsms.util.Util;


public class Main extends MIDlet implements CommandListener {

	private Display display;
	private Command sendCommand;
	private Command exit;
	private Command sendAgainCommand;
	private Command reloadCommand;
	
	private Builder builder;
		
	public Main() throws IOException {
		this.display = Display.getDisplay(this);
		this.builder = new Builder();
		
		// commands
		this.sendCommand = new Command("Send", Command.SCREEN, 1);
		this.sendAgainCommand = new Command("Send again", Command.SCREEN, 1);
		this.reloadCommand = new Command("Reload", Command.SCREEN, 2);
		this.exit = new Command("Exit", Command.EXIT, 1);
	}
	
	private void loadStartScreen() {
		Runnable op = new Runnable() {
			public void run() {
				try {
					builder.clear();
					// download and parse the web form
					FormParser p = new FormParser("http://sms.megafonmoscow.ru");
					p.addListener(builder);
					p.run();

					// ... then show the result of our work ...
					UIFormBuilder b = new UIFormBuilder();
					FormModel model = builder.getModel("smsForm");
					// send_after_flag should be off by default
					model.getControl("send_after_flag").setValue(null);
					// my favourite number :)
					model.getControl("addr").setValue("5886548");
					// enable transliterate
					model.getControl("transliterate").setValue("on");
					b.setModel(model);
					b.addModifier(new MegafonModifier());
					b.addModifier(new ItemLocalizer("en"));
					Form f = b.buildUIForm();
					f.addCommand(sendCommand);
					f.addCommand(reloadCommand);
					f.addCommand(exit);
					f.setCommandListener(Main.this);

					// download captcha picture
					// http://sms.megafonmoscow.ru/image.phtml?k=
					InputFormControl code = (InputFormControl) builder
							.getModel("smsForm").getControl("codekey");
					Image i = Util.downloadImage("http://sms.megafonmoscow.ru/image.phtml?k="
									+ code.getValue());
					f.append(i);
					
					display.setCurrent(f);
				} catch (IOException ex) {
					SimpleDisplay errorDisp = new SimpleDisplay("Error",
							"An error occurred during downloading of inital page.\nDetail: "
									+ ex.toString());
					errorDisp.addCommand(exit);
					errorDisp.setCommandListener(Main.this);
					display.setCurrent(errorDisp);
				}
			}
		};

		Util.runAsync(op, "Initializing ...",
				"Loading initial form, please wait", this.display);
	}

	/* (non-Javadoc)
	 * @see javax.microedition.midlet.MIDlet#startApp()
	 */
	protected void startApp() throws MIDletStateChangeException {
		loadStartScreen();
	}

	/* (non-Javadoc)
	 * @see javax.microedition.lcdui.CommandListener#commandAction(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable)
	 */
	public void commandAction(Command c, Displayable d) {
		if (c == this.sendCommand) {
			// TODO: check if all values are correctly filled
			
			Runnable run = new Runnable() {
				public void run() {
					// send the HTTP POST with data from form
					FormModel smsForm = builder.getModel("smsForm");
					String url = "http://sms.megafonmoscow.ru" + smsForm.getFormAction();
					try {
						String res = Util.sendForm(smsForm, url);
						// show screen about sccessfull sending
						SimpleDisplay sucDisp = new SimpleDisplay("Success",
								"SMS sent successfuly !\n Detail: " + res);
						sucDisp.addCommand(sendAgainCommand);
						sucDisp.addCommand(exit);
						sucDisp.setCommandListener(Main.this);
						display.setCurrent(sucDisp);
					} catch (IOException ex) {
						SimpleDisplay errorDisp = new SimpleDisplay("Failure",
								"SMS send failed !\n Detail: " + ex.toString());
						errorDisp.addCommand(sendAgainCommand);
						errorDisp.addCommand(exit);
						errorDisp.setCommandListener(Main.this);
						display.setCurrent(errorDisp);
					}
				}
			};
			
			Util.runAsync(run, "Sending SMS", null, this.display);
			
		} else if (c == this.exit) {
			this.notifyDestroyed();
		} else if (c == this.sendAgainCommand || c == reloadCommand) {
			loadStartScreen();
		}
	}
	
	/* (non-Javadoc)
	 * @see javax.microedition.midlet.MIDlet#destroyApp(boolean)
	 */
	protected void destroyApp(boolean unconditional)
			throws MIDletStateChangeException {}

	/* (non-Javadoc)
	 * @see javax.microedition.midlet.MIDlet#pauseApp()
	 */
	protected void pauseApp() {}


}
